package com.zzzzzz.account;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zzzzzz.core.exception.NoSuchUserException;

@Service
public class ShiroDbRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;
	
	public ShiroDbRealm() {
		setName("shiroDbRealm"); //This name must match the name in the User class's getPrincipals() method
        setCredentialsMatcher(new Sha256CredentialsMatcher());
	}

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = null;
		try {
			user = userService.findByEmail(token.getUsername());
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
				logger.error(e.getMessage());
			}else {
				logger.error(e.getMessage(), e);
			}
		}
        if(user != null) {
            return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
        } else {
            return null;
        }
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userId = (String) principals.fromRealm(getName()).iterator().next();
        User user = null;
        try {
			user = userService.findById(new Long(userId));
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
				logger.error(e.getMessage());
			}else {
				logger.error(e.getMessage(), e);
			}
		}
		if(user != null) {
    		Set<String>	roleNames = new HashSet<String>();
    		String email = user.getEmail();
    		if("gozizibj@gmail.com".equalsIgnoreCase(email) || "kougua@gmail.com".equalsIgnoreCase(email)) {
    			roleNames.add("administrator");
    		}
        	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        	info.setRoles(roleNames);
        	
			return info;
        }else{
        	return null;
        }
    }
	
    private static final Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

}
